package com.mianle.userapi.config;


import com.alibaba.fastjson.JSON;
import com.mianle.userapi.util.HttpUtil;
import com.mianle.userapi.util.JsonResponseData;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class AccessSafeFilter implements Filter {

    private int isDug;
    private String jwtSalt;
    private String noCheckUrl;
    private String dispatchFilterErrorUrl;
    private List<String> whiteIpList;
    private String suffixs;

    private static final Logger log = LoggerFactory.getLogger(AccessSafeFilter.class);



    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String url = httpServletRequest.getRequestURI();

        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); //解决跨域访问报错


        String token = httpServletRequest.getHeader("authorization");


        String ip = HttpUtil.getIpAddr(httpServletRequest);
        if (whiteIpList.contains(ip)) {
            filterChain.doFilter(request, response);
            return;
        }

        String[] urlArray = url.split("/");

        String[] allowPath = this.noCheckUrl.split(",");
//        ServletContext context = request.getServletContext();
//        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
//        ResourceConfig resourceConfig = ctx.getBean(ResourceConfig.class);
//        String suffixs = resourceConfig.getNoChecKSuffixs();

        //注意这里根据URI取用户端API不同模块 eg:
        if (ArrayUtils.contains(allowPath, urlArray[2])  && StringUtils.isEmpty(token)) {
            filterChain.doFilter(request, response);
            return;
        }

        //静态资源特殊处理
        boolean isExist = checkSuffix(urlArray[2], suffixs.split(","));
        if(isExist) {
            filterChain.doFilter(request, response);
            return;
        }

        if (StringUtils.isNotEmpty(token)) {
            Claims claims = null;
            try {
                claims = Jwts.parser().setSigningKey(this.jwtSalt).parseClaimsJws(token).getBody();
            } catch (Exception e) {
                log.error("#AccessSafeFilter.doFilter# token:{} e:{}", token, e.getMessage());
            }

            if (claims != null) {
                httpServletRequest.setAttribute("jwt_info", claims);
                filterChain.doFilter(request, response);
                return;
            }
        }

        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);


        JsonResponseData result = new JsonResponseData<>(2, "未认证（签名错误）", "");
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
        return;


    }

    @Override
    public void init(FilterConfig filterConfig) {
        this.isDug = Integer.valueOf(filterConfig.getInitParameter("is_debug"));
        this.jwtSalt = filterConfig.getInitParameter("jwt_salt");
        this.noCheckUrl = filterConfig.getInitParameter("no_check_url");
        this.dispatchFilterErrorUrl = "/public_tip/filter_error";
        whiteIpList = new ArrayList<>();
        whiteIpList.add("120.79.249.241");
        this.suffixs = filterConfig.getInitParameter("suffixs");
    }

    public static void main(String[] args) {
        String string = "img,png,gif";
        String img = "fsdfs.png";

        System.out.println("--------------- " + checkSuffix(img, string.split(",")));
    }

    public static boolean checkSuffix(String fileName, String[] suffixArray) {
        if (fileName.indexOf(".") == -1) {
            return false;
        }
        String suffix = fileName.substring(fileName.indexOf(".") + 1);
        return ArrayUtils.contains(suffixArray, suffix);
    }

    public static String getSuffix(String fileName) {
        if (fileName.indexOf(".") == -1) {
            return "";
        }
        return fileName.substring(fileName.indexOf(".") + 1);
    }
}
